<?php

/**
 * 区块操作
 * @author M2
 * @version 1.0
 * create Date 2013-07-22
 */
class BlockAction extends PublicAction {

    public function show() {
        if (isset($_GET['tid']) && isset($_GET['id']) && isset($_GET['type'])) {
            $this->assign('tid', $_GET['tid']);
            $this->assign('id', $_GET['id']);
            $this->assign('type', $_GET['type']);
        }
        $this->display();
    }

    /**
     * 获取区块信息	
     * M2
     */
    public function getBlockInfo() {
        $classify = M('cms_blockclassify')->order('id')->select();
        $arr = array();
        foreach ($classify as $k => $v) {
            $arr [] = array(
                'id' => $v ['id'],
                'type' => 'classify',
                'open' => true,
                'name' => $v ['classify_name'],
                'isParent' => true
            );
            $where = array(
                'cid' => $v['id'],
                'type' => 1, //普通区块
            );
            $block = M('cms_block')->where($where)->select();
            foreach ($block as $kk => $vv) {
                $arr [$k] ['children'][] = array(
                    'id' => $vv ['id'],
                    'type' => 'block',
                    'open' => true,
                    'name' => $vv ['name']
                );
            }
        }
        $blocktree = array(
            'id' => 0,
            'type' => 'blockclassify',
            'open' => true,
            'name' => '区块分类',
            'isParent' => true,
            'children' => $arr
        );
        echo json_encode($blocktree);
    }

    public function ajax_show() {
        $arr = array();
        if (!empty($_GET['id']) && !empty($_GET['type'])) {
            if ($_GET['type'] == 'classify') {
                $id = intval($_GET['id']);
                $findClassify = M('cms_blockclassify')->where("id=$id")->find();
                $list = M('cms_block')->where("cid=$id")->order('updatetime desc')->select();
                $this->assign("id", $id);
                $this->assign("type", 'classify');
                $this->assign("daohang", '->' . $findClassify['classify_name']);
                $this->assign("list", $list);
                $this->display("blocklist");
            } else if ($_GET['type'] == 'block') {
                $id = intval($_GET['id']);
                $findBlock = M('cms_block')->where("id=$id")->find();
                $findClassify = M('cms_blockclassify')->where("id={$findBlock['cid']}")->find();
                $bid = $findBlock['content_number'];
                $data['id'] = array('in', $bid);
                import('ORG.Util.Page');
                $count = M('cms_article')->where($data)->count();
                $page = new Page($count, 20);
                $list = M('cms_article')->where($data)->limit($page->firstRow . ',' . $page->listRows)->select();


                $domain = M('cms_site')->where("siteid = 1")->getField("domain");
                foreach ($list as $k => $v) {
                    $curdomain = D('Site')->getSiteDomain($list[$k]['siteid']);
                    if (strpos($v['imageurl'], "@") === 0) {
                        $list[$k]['imageurl'] = $curdomain . substr($list[$k]['imageurl'], 1);
                    } elseif (strpos($v['imageurl'], "/") === 0) {
                        if (strpos($v['imageurl'], __ROOT__ . "/") === 0)
                            continue;
                        $list[$k]['imageurl'] = $curdomain . $list[$k]['imageurl'];
                    }elseif (strpos($v['imageurl'], "~") === 0) {
                        $list[$k]['imageurl'] = $domain . $list[$k]['imageurl'];
                    }
                }

                $this->assign("id", $id);
                $this->assign("type", 'block');
                $this->assign("cid", $_GET['cid']);
                $this->assign("daohang", '-><a href="' . URL('cms/Block/ajax_show', array('id' => $findClassify['id'], 'type' => 'classify')) . '" style="color:#fff;">'
                        . $findClassify['classify_name'] . '</a>->' . $findBlock['name']);
                $this->assign("page", $page->show());
                $this->assign("list", $list);
                $this->display("contentlist");
            }
        }
    }

    /**
     * 添加区块内容页	
     * M2
     */
    public function addblock_content() {
        if (!empty($_GET['type']) && !empty($_GET['id'])) {
            if ($_GET['type'] == 'classify') {
                if (!empty($_GET['blockid'])) {
                    $data['id'] = intval($_GET['blockid']);
                    $findBlock = M('cms_block')->where($data)->find();
                    $this->assign('findBlock', $findBlock);
                    $this->assign('blockid', intval($_GET['blockid']));
                }
                $this->assign('id', intval($_GET['id']));
                $this->assign('tid', $_GET['tid']);
                $this->display('addblock');
            }
            if ($_GET['type'] == 'block') {
                $this->assign('id', intval($_GET['id']));
                $this->assign('tid', $_GET['tid']);
                $this->assign('cid', $_GET['cid']);
                $this->display();
            }
        }
    }

    /**
     * 添加区块页操作	
     * M2
     */
    public function doaddblock() {
        if ($_POST) {
            if (!empty($_POST['id'])) {
                $data ['cid'] = intval($_POST['id']);
            }
            $data['name'] = trim($_POST['blockname']);
            $findBlock = M('cms_block')->where($data)->find();
            if ($findBlock)
                $this->error('区块名称已存在');
            $data['template'] = stripcslashes(trim($_POST['template']));
            $data['number'] = intval($_POST['number']);
            if ($data['number'] === 0) {
                $data['number'] = 5;
            }
            $data['remark'] = common('Html')->text(trim($_POST['remark']));
            $data['create_uid'] = $this->mid;
            $data['create_uname'] = common('String')->getUserName($this->mid);
            $data['update_uid'] = $this->mid;
            $data['update_uname'] = common('String')->getUserName($this->mid);
            $data['inputtime'] = time();
            $data['updatetime'] = time();
            $data['type'] = in_array($_POST['type'], array(1, 2)) ? $_POST['type'] : 1;
            if ($blockId = M('cms_block')->add($data)) {
                if ($data['type'] == 2) {
                    //生成静态区块
                    if ($this->createStaticBlock($blockId)) {
                        $this->assign('jumpUrl', URL('cms/Block/ajax_show', array('type' => 'classify', 'id' => intval($_POST['id']), 'tid' => $_POST['tid'])));
                        $this->success('操作成功');
                    } else {
                        $this->error('静态区块生成失败');
                    }
                } else {
                    $this->assign('jumpUrl', URL('cms/Block/ajax_show', array('type' => 'classify', 'id' => intval($_POST['id']), 'tid' => $_POST['tid'])));
                    $this->success('操作成功');
                }
            } else {
                $this->error('操作失败');
            }
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 修改区块
     * M2
     */
    public function doupdateblock() {
        if ($_POST) {
            if (!empty($_POST['id']) && !empty($_POST['blockid'])) {
                $data ['id'] = array('neq', intval($_POST['blockid']));
                $data ['cid'] = intval($_POST['id']);
            }
            $data['name'] = trim($_POST['blockname']);
            $findBlock = M('cms_block')->where($data)->find();
            if ($findBlock)
                $this->error('区块名称已存在');
            unset($data['id']);
            $data['cid'] = intval($_POST['id']);
            $data['number'] = intval($_POST['number']);
            if ($data['number'] === 0) {
                $data['number'] = 5;
            }
            $data['template'] = stripcslashes(trim($_POST['template']));
            $data['remark'] = common('Html')->text(trim($_POST['remark']));
            $data['update_uid'] = $this->mid;
            $data['update_uname'] = common('String')->getUserName($this->mid);
            $data['updatetime'] = time();
            $data['type'] = in_array(intval($_POST['type']), array(1, 2)) ? intval($_POST['type']) : 1;
            $result = M('cms_block')->where('id=' . intval($_POST['blockid']))->save($data);
            if (false !== $result) {
                if ($data['type'] == 2) {
                    //生成静态区块
                    if ($this->createStaticBlock(intval($_POST['blockid']))) {
                        $this->assign('jumpUrl', URL('cms/Block/ajax_show', array('type' => 'classify', 'id' => intval($_POST['id']), 'tid' => $_POST['tid'])));
                        $this->success('操作成功');
                    } else {
                        $this->error('静态区块生成失败');
                    }
                } else {
                    $this->assign('jumpUrl', URL('cms/Block/ajax_show', array('type' => 'classify', 'id' => intval($_POST['id']), 'tid' => $_POST['tid'])));
                    $this->success('操作成功');
                }
            } else {
                $this->error('操作失败');
            }
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 删除区块
     * M2
     */
    public function delBlock() {
        if (session('mid') !== "100000000") {
            echo 0;
            return;
        }
        if (empty($_POST ['ids'])) {
            echo 0;
            exit();
        }
        $data['id'] = array('in', $_POST['ids']);
        $list = M('cms_block')->where($data)->select();
        if (empty($list)) {
            echo 0;
            exit();
        }
        $templatePath = './Public/cms/html/';
        foreach ($list as $k => $v) {
            $filename = $templatePath . iconv("UTF-8", "GB2312", 'block/' . $v['name']) . '.html';
            if (file_exists($filename))
                unlink($filename);
        }
        echo M('cms_block')->where($data)->delete() ? 1 : 0;
    }

    /**
     * 生成静态区块
     * @param array|int $blockIds 要生成的静态区块
     * @return boolean true|false
     */
    private function createStaticBlock($blockIds) {
        if (empty($blockIds)) {
            return false;
        }
        if (is_array($blockIds)) {
            $blocks = implode(",", $blockIds);
        } else {
            $blocks = intval($blockIds);
        }
        $where = array(
            'id' => array('in', array($blocks))
        );
        $blockInfo = M('cms_block')->where($where)->field('id,template,name,content_number,number')->select();
        $templatePath = './Public/cms/html/';
        foreach ($blockInfo as $k => $v) {
            if (!file_exists($templatePath)) {
                mk_dir($templatePath);
            }
            $filename = $templatePath . md5($v['name']) . '.html';

            file_put_contents($filename, $v['template']);
            if (file_exists($filename)) {
                if ($this->buildHtml(iconv("UTF-8", "GB2312", 'block/' . $v['name']) . '.html', $templatePath, $filename) ||
                        file_exists($templatePath . iconv("UTF-8", "GB2312", 'block/' . $v['name']) . '.html')
                ) {
                    unlink($filename);
                    unset($data);
                    $data['content_number'] = implode(',', $newarr);
                    $blockid = intval($v['id']);
                    M('cms_block')->where("id=$blockid")->save($data);
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 生成区块
     * M2
     * <yl:block sql="" value="data"></yl:block>
     */
    public function createBlock($arrId, $blockId) {
        $arr_id = empty($_POST['arr']) ? $arrId : $_POST['arr'];
        $block_id = empty($_POST['block_id']) ? $blockId : $_POST['block_id'];
        if (!empty($arr_id)) {
            if (!empty($block_id)) {
                $data['id'] = array('in', $block_id);
                $block = M('cms_block')->where($data)->field('id,template,name,content_number,number')->select();
                foreach ($block as $k => $v) {
                    if ($v['content_number']) {
                        $oldarr = explode(',', $v['content_number']);
                        foreach ($arr_id as $arrv) {
                            if (in_array($arrv, $oldarr)) {
                                $unset_key = array_search($arrv, $oldarr);
                                unset($oldarr[$unset_key]);
                            }
                        }
                        foreach ($arr_id as $arrv) {
                            array_push($oldarr, $arrv);
                        }
                        $newarr = array_unique($oldarr);
                    } else {
                        $newarr = $arr_id;
                    }

                    $map = array(
                        'id' => array('in', $newarr),
                    );
                    //得到全局配置
                    //获得站点id
                    $siteInfo = M('cms_article')->where($map)->field('siteid')->find();
                    $globalConfig = model('Data')->get('cmsconfig:site-' . $siteInfo['siteid']);
                    $sql = 'select (case when url <> "" then url else
                                (concat(S.domain,"/",replace(replace(
                                (case when (select A.artnaming from '.$this->_dbPrefix.'cms_category A where A.id=cid) <> "" then (select A.artnaming from '.$this->_dbPrefix.'cms_category A where A.id=cid) else "' . $globalConfig['artnaming'] . '" end),
                                "{cateid}",cid),"{contentid}",id))) end) as url,replace(imageurl,"@",S.domain)as imageurl,
                                replace(big_imageurl,"@",S.domain) as big_imageurl,S.domain,@row := @row + 1 as ItemIndex,art.id,
                                art.siteid,art.cid,art.classid,art.title,art.subtitle,art.author,art.source,art.summary,art.content,
                                art.readpoint,art.keywords,art.description,art.display_order,art.create_uid,art.create_uname,art.update_uid,
                                art.update_uname,art.iscomment,art.status,art.fileurl,art.arttemplate,art.inputtime,art.updatetime,
                                art.is_recommend,art.is_hot,art.is_color,art.is_top,art.is_index_news,art.tags,art.group_name_collection,
                                art.related_node_list,art.related_articles,art.istransfer,art.weight,art.articledate,art.comment_count
                                from (select @row := 0) r,'.$this->_dbPrefix.'cms_article art left join '.$this->_dbPrefix.'cms_site S on art.siteid=S.siteid
                                where id in('. implode(',', $newarr) .') and art.status=1
                                order by find_in_set(id,"'. implode(',', array_reverse($newarr)) .'") limit '.$v['number'];
              
                    S('cache_sqlcontents_'.$sql, null);

                    $template = htmlspecialchars_decode($v['template']);
                    $parseStr = '<yl:sqlContents>';
                    $parseStr .= '<yl:queryString>' . $sql . '</yl:queryString>';
                    $parseStr .= $template;
                    $parseStr .= '</yl:sqlContents>';
                    $templatePath = './Public/cms/html/';
                    if (!file_exists($templatePath)) {
                        mk_dir($templatePath);
                    }
                    $filename = $templatePath . md5($v['name']) . '.html';
                    
                    $content = taglib('YlSqlContents')->parse($parseStr);
                    file_put_contents($filename, $content);
                    if (file_exists($filename)) {
                        if ($this->buildHtml(iconv("UTF-8", "GB2312", 'block/' . $v['name']) . '.html', $templatePath, $filename) || file_exists($templatePath . iconv("UTF-8", "GB2312", 'block/' . $v['name']) . '.html')) {
                            unlink($filename);
                            unset($data);
                            $data['content_number'] = implode(',', $newarr);
                            $blockid = intval($v['id']);
                            M('cms_block')->where("id=$blockid")->save($data);
                        }
                    }
                }
                if (empty($arrId)) {
                    echo 1;
                }
            } else {
                if (empty($arrId)) {
                    echo '区块未选择';
                }
            }
        } else {
            if (empty($arrId)) {
                echo '文章未选择';
            }
        }
    }
    
    /*
     * 删除区块内容
     * M2
     */

    public function delBlockContent() {
        $id = intval($_POST['id']);
        $contentid = intval($_POST['contentid']);
        $content_number = M('cms_block')->where(array('id' => $id))->getField('content_number');
        $cn = explode(',', $content_number);
        $arr = array();
        foreach ($cn as $v) {
            if ($v == $contentid) {
                continue;
            }
            $arr[] = $v;
        }
        $data['content_number'] = implode(',', $arr);
        if (false !== M('cms_block')->where(array('id' => $id))->save($data)) {
            echo 1;
        } else {
            echo 0;
        }
    }

    public function openFile() {
        $name = urldecode($_GET['name']);

        $fileurl = './Public/cms/html/block/' . iconv('UTF-8', 'GB2312', $name) . '.html';

        echo read_file($fileurl);
    }

}

?>